import api from './api'

// 获取更新信息
const getUpdateInfo = () => {
    return new Promise(async resolve => {
        const res = await api.common.getUpdateInfo()
        if (res.success) {
            resolve(res.data)
        } else {
            resolve()
        }
    })
    
}

// 获取客户端版本
const getClientVersion = () => {
    return new Promise(resolve => {
        plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
            resolve(widgetInfo.version)
        })
    })
}

// 下载热更新包
const downloadWgt = url => {
    return new Promise((resolve, reject) => {
        uni.downloadFile({
            url,
            success: res => {
                resolve(res)
            },
            fail: err => {
                console.log('更新下载失败', err)
                reject('更新下载失败')
            }
        })
    })
}

// 安装热更新包
const installWgt = file => {
    return new Promise((resolve, reject) => {
        plus.runtime.install(file.tempFilePath, {force: true},
                () => {
                    resolve()
                },
                () => {
                    reject('更新安装失败')
                })
    })
}

export default async function () {
    // #ifdef APP-PLUS
    try {
        if (plus.runtime.appid === 'HBuilder'){
            return
        }
        const updateInfo = await getUpdateInfo()
        if (updateInfo) {
            const clientVersion = await getClientVersion()
            if (clientVersion === updateInfo.versionName) {
                return
            }
            const wgt = await downloadWgt(updateInfo.fileObject.path)
            await installWgt(wgt)
            plus.runtime.restart()
        }
    } catch (err) {
        console.log('热更新失败', err)
    }
    // #endif
    // #ifndef APP-PLUS
    console.log('不支持更新')
    // #endif
    
}


